import { createSlice } from '@reduxjs/toolkit';
import { REHYDRATE } from 'redux-persist';
import { userList } from '../../api/user';

// 用户列表项类型
export interface UserListItem {
  email: string;
  pwd: string;
  isAdmin: boolean;
}

// 用户列表状态
interface UserListState {
  users: UserListItem[];
  isInitialized: boolean; // 添加初始化标志
}

// 检查是否有持久化数据的辅助函数
const getInitialUsersFromStorage = (): UserListItem[] => {
  try {
    const persistedState = localStorage.getItem('persist:root');
    if (persistedState) {
      const parsed = JSON.parse(persistedState);
      if (parsed.userList) {
        const userListData = JSON.parse(parsed.userList);
        if (userListData.users && Array.isArray(userListData.users) && userListData.users.length > 0) {
          console.log('从localStorage获取初始userList数据:', userListData.users);
          return userListData.users;
        }
      }
    }
  } catch (error) {
    console.error('从localStorage读取userList数据失败:', error);
  }
  console.log('使用默认userList数据作为初始值:', userList);
  return userList;
};

// 初始状态 - 尝试从localStorage获取数据，否则使用默认数据
const initialState: UserListState = {
  users: getInitialUsersFromStorage(),
  isInitialized: false,
};

// 创建用户列表 slice
const userListSlice = createSlice({
  name: 'userList',
  initialState,
  reducers: {
    // 更新用户列表
    setUsers: (state, action) => {
      state.users = action.payload;
    },
    // 重置到默认数据
    resetToDefault: (state) => {
      state.users = userList;
      console.log('重置到默认userList数据:', userList);
    },
    // 初始化完成
    setInitialized: (state, action) => {
      state.isInitialized = action.payload;
    },
  },
  extraReducers: (builder) => {
    // 处理redux-persist的REHYDRATE action
    builder.addCase(REHYDRATE, (state, action: any) => {
      console.log('REHYDRATE action triggered:', action.payload);

      // 只有在当前数据是默认数据且存在持久化数据时才更新
      if (action.payload && action.payload.userList) {
        const persistedUserList = action.payload.userList;
        if (persistedUserList.users && Array.isArray(persistedUserList.users) && persistedUserList.users.length > 0) {
          // 检查当前数据是否是默认数据（通过比较第一个用户的邮箱）
          const isCurrentDataDefault = state.users.length > 0 &&
            state.users[0].email === userList[0].email;

          if (isCurrentDataDefault) {
            console.log('当前是默认数据，使用持久化的userList数据:', persistedUserList.users);
            state.users = persistedUserList.users;
          } else {
            console.log('当前已有修改过的数据，保持当前数据:', state.users);
          }
        }
      }
      state.isInitialized = true;
    });
  },
});

// 导出 actions
export const { setUsers, resetToDefault, setInitialized } = userListSlice.actions;

// 导出 reducer
export default userListSlice.reducer;